package com.cpi.cornpp.languaje.services;

import java.util.List;

import com.cpi.cornpp.common.exception.CornPPException;
import com.cpi.cornpp.languaje.converter.LanguageConverter;
import com.cpi.cornpp.languaje.dao.LanguageDAO;
import com.cpi.cornpp.languaje.dto.LanguageDTO;
import com.cpi.cornpp.languaje.exception.LanguageException;
import com.cpi.cornpp.languaje.view.LanguageView;

/**
 * Languae Service
 * @author Edgar Joao
 *
 */
public class LanguageService {
	/**
	 * 
	 * @param languageView
	 * @throws LanguageException
	 */
	public void addUserLanguage(LanguageView languageView) throws LanguageException{			
		LanguageDAO languageDAO = null;		
		LanguageConverter languageConverter = null;
		LanguageDTO languageDTO = null;		
								
		try {
			
			languageDAO = new LanguageDAO();
			languageDTO = new LanguageDTO();
			languageConverter = new LanguageConverter();
			
			// La vista la convierto en un DTO
			languageDTO = languageConverter.convertLanguageViewToDto(languageView);						
			if(!languageDAO.existUserAndLanguage(languageDTO)){
				languageDAO.insertLanguageUser(languageDTO);
			}else{
				languageDAO.updateIfExistUserLanguage(languageDTO);
			}
		} catch (LanguageException languageException ){
			throw languageException;
		} catch (Exception e) {
			LanguageException languageException = null;
			e.printStackTrace(System.out);
			languageException = new LanguageException(e , CornPPException.LAYER_SERVICE,CornPPException.ACTION_INSERT);
			throw languageException;
		}
	}
	
	public List getLanguages()throws LanguageException{
		List languageViews = null;
		LanguageDAO languageDAO = null;
		List languageDTOs = null;
		LanguageConverter languageConverter = null; 
		
		try{
			languageDAO = new LanguageDAO();
			languageConverter = new LanguageConverter();
			languageDTOs = languageDAO.getListOfLanguajes();
			languageViews = languageConverter.convertDTOsToViews(languageDTOs);
		}catch( LanguageException languageException){
			throw languageException;
		}catch(Exception exception){
			LanguageException languageException = null;
			exception.printStackTrace(System.out);
			languageException = new LanguageException(exception , CornPPException.LAYER_SERVICE,CornPPException.ACTION_LISTS);
			throw languageException;
		}
		
		return languageViews;
	}
}